package com.sunday.common.sharding.sphere.jdbc.leaf.algorithm.sharding.interval;

import com.sunday.common.leaf.core.IdWorker;
import org.apache.shardingsphere.sharding.exception.ShardingPluginException;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Properties;

/**
 * leaf 雪花分片策略
 * 参考 : org.apache.shardingsphere.sharding.cosid.algorithm.sharding.interval.CosIdSnowflakeIntervalShardingAlgorithm
 *
 * @author zsy
 * @since 2022/12/29
 */
public final class LeafSnowflakeIntervalShardingAlgorithm extends AbstractLeafIntervalShardingAlgorithm {

    @Override
    public void init(final Properties props) {
        super.init(props);
    }

    @Override
    protected LocalDateTime snowflakeShardingValue(final Comparable<?> shardingValue) {
        if (shardingValue instanceof Long value) {
            return IdWorker.parseId(value);
        }
        if (shardingValue instanceof String value) {
            return IdWorker.parse62Id(value);
        }
        throw new ShardingPluginException("Unsupported sharding value type `%s`.", shardingValue);
    }

    @Override
    protected LocalDateTime dateTimeShardingValue(final Comparable<?> shardingValue) {
        if (shardingValue instanceof LocalDateTime localDateTime) {
            return localDateTime;
        }
        if (shardingValue instanceof LocalDate localDate) {
            return localDate.atTime(LocalTime.MIN);
        }
        throw new ShardingPluginException("Unsupported sharding value type `%s`.", shardingValue);
    }

}
